﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using MINERP.MODEL.GroupSample;
using MINERP.DAL;
using MINERP.COM;
using Leadtools.Codecs;
using Leadtools;

using Leadtools.ImageProcessing;
using System.ComponentModel;
using MINERP.BLL.Common;

using MINERP.MODEL.FoundationModel;

namespace MINERP.BLL.GroupSample
{
    public class GroupSampleBLL
    {
        private WorkFlowListBLL _workFlowBll = new WorkFlowListBLL();
        /// <summary>
        /// 获取任务列表
        /// </summary>
        /// <param name="userId">员工姓名</param>
        /// <param name="IsAllTask">是否显示看样岗位所有任务</param>
        /// <returns></returns>
        public List<TaskInfo> GetListTask(int userId,bool IsAllTask)
        {
    
            List<TaskInfo> taskList = new List<TaskInfo>();
            if (userId != 0)
            {
                using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
                {

                    List<WorkOrderFlowList> wflList = null;
                    tb_Tech tech = DataEntites.tb_Tech.FirstOrDefault(t => t.TechName.Contains("看样"));
             
                    if (tech == null)
                        throw new Exception("不存在“看样”节点");
                    if (!tech.WorkOrderFlowList.IsLoaded)
                    {
                        tech.WorkOrderFlowList.Load();
                    }
                    if (IsAllTask)//所有看样节点的任务
                    {
                        wflList = tech.WorkOrderFlowList.Where(wlf => wlf.Status ==(int)OrderFlowListStatus.Useable).ToList();
                    }
                    else//当前员工在看样节点所接收的任务
                    {
                        wflList = tech.WorkOrderFlowList.Where(wl => wl.UserId == userId).ToList().Where(wlf => wlf.Status == (int)OrderFlowListStatus.Useable).ToList();
                    }
                    foreach (var wofl in wflList)
                    {
                        #region 数据加载
                        if (!wofl.orderInfoReference.IsLoaded)
                        {
                            wofl.orderInfoReference.Load();
                        }

                        if (wofl.orderInfo.status != (int)OrderInfoStatus.Doing)
                        {
                            continue;
                        }

                        if (!wofl.orderInfo.Tb_OrderBagReference.IsLoaded)
                        {
                            wofl.orderInfo.Tb_OrderBagReference.Load();
                        }
                        if (!wofl.orderInfo.Tb_ProductReference.IsLoaded)
                        {
                            wofl.orderInfo.Tb_ProductReference.Load();
                        }
                        if (!wofl.orderInfo.Tb_OrderBag.ShopReference.IsLoaded)
                        {
                            wofl.orderInfo.Tb_OrderBag.ShopReference.Load();
                        }
                        if (!wofl.tb_TechReference.IsLoaded)
                        {
                            wofl.tb_TechReference.Load();
                        }
                        if (!wofl.orderInfo.photoInfo.IsLoaded)
                        {
                            wofl.orderInfo.photoInfo.Load();
                        }

                        #endregion

                        TaskInfo ti = new TaskInfo()
                        {
                            OrderProductId = wofl.orderInfo.OrderProductId,
                            CtmName = wofl.orderInfo.CtmName,
                            OrderProductName = wofl.orderInfo.OrderProductName,
                            ProductNum = wofl.orderInfo.productNum,
                            Priority = (int)wofl.orderInfo.Priority,
                            ShopName = wofl.orderInfo.Tb_OrderBag.Shop.shopName,
                            ShopId = wofl.orderInfo.Tb_OrderBag.Shop.ShopId,
                            status = wofl.Status,
                            PageNum = wofl.orderInfo.photoInfo.Count,
                            ProductName = wofl.orderInfo.Tb_Product.ProductName,
                            ProductSize = wofl.orderInfo.Tb_Product.Width.ToString() + "*" + wofl.orderInfo.Tb_Product.Height.ToString(),
                            ProductRemark = wofl.orderInfo.Remark,
                            TechId = wofl.tb_Tech.TechId,
                            TechName = wofl.tb_Tech.TechName,
                            IsDeisgnTech = wofl.tb_Tech.IsDesign,
                            IsRebackOrder = false,
                            OrderPath = wofl.orderInfo.OrderPath,
                            workflowlistId =wofl.WorkFlowListId,
                            orderBagID=wofl.orderInfo.Tb_OrderBag.OrderBagId
                             
                        };
                        if (wofl.AssignTime == wofl.ReceiveTime)
                        {
                            ti.SmallPicStatus = "未发样";
                        }
                        else
                        {
                            ti.SmallPicStatus = "已发样";
                        }


                        if (wofl.orderInfo.photoInfo.FirstOrDefault() != null)//产品有照片
                        {
                            if (!wofl.orderInfo.photoInfo.First().paperFaceReference.IsLoaded)
                            {
                                wofl.orderInfo.photoInfo.First().paperFaceReference.Load();
                            }
                            if (!wofl.orderInfo.photoInfo.First().paperTypeReference.IsLoaded)
                            {
                                wofl.orderInfo.photoInfo.First().paperTypeReference.Load();
                            }
                            ti.PaperFaceName = wofl.orderInfo.photoInfo.First().paperFace.Name;
                            ti.PaperTypeName = wofl.orderInfo.photoInfo.First().paperType.Name;
                            int printerId = (int)wofl.orderInfo.photoInfo.First().printerId;
                            printer printer = DataEntites.printer.FirstOrDefault(p => p.PrinterID == printerId);
                            if (printer != null)
                            {
                                ti.PrinterName = printer.PName;
                            }
                            else
                            {
                                ti.PrinterName = "";
                            }
                        }
                        else
                        {
                            ti.PaperFaceName = "";
                            ti.PaperTypeName = "";
                            ti.PrinterName = "";
                        }
                        ti.PhotoList = new List<PhotoInfo_GM>();
                        List<photoInfo> Plist = wofl.orderInfo.photoInfo.ToList();
                        foreach (var p in Plist)
                        {
                            if (!p.paperTypeReference.IsLoaded)
                            {
                                p.paperTypeReference.Load();
                            }
                            if (!p.paperFaceReference.IsLoaded)
                            {
                                p.paperFaceReference.Load();
                            }

                            PhotoInfo_GM pgm = new PhotoInfo_GM()
                            {
                                Height = p.Height,
                                IsEdit = false,
                                PicPath = p.picPath,
                                PhotoName = p.photoName,
                                Width = p.Width,
                                PhotoBarCode = p.PhotoBarCode,
                                PhotoId = p.photoId,
                                Remark = p.Remark,
                                OldPicPath = p.OldPicPath,
                                IsRebackPhoto = (p.status2 == (int)PhotoStatus2.innerReturn) ? true : false,
                                PaperFaceName = p.paperFace.Name,
                                PaperTypeName = p.paperType.Name
                            };
                            printer printer = DataEntites.printer.FirstOrDefault(pr => pr.PrinterID == p.printerId);
                            if (printer != null)
                            {
                                pgm.PrinterName = printer.PName;
                            }
                            else
                            {
                                pgm.PrinterName = "";
                            }
                       
                            ti.PhotoList.Add(pgm);
                     
                        }
                        ti.PhotoList = ti.PhotoList.OrderByDescending(p => p.IsRebackPhoto).ToList();//返单的照片在前面

              

                        taskList.Add(ti);
                    }
                }
            }
            taskList = taskList.OrderByDescending(t => t.Priority).ToList();
            return taskList;
        }

        public List<TaskInfo> GetListTask(int userId, bool IsAllTask,List<Tb_Tech_Info> listTech)
        {

            List<TaskInfo> taskList = new List<TaskInfo>();
            if (userId != 0)
            {
                using (newSampleYPDBEntities DataEntites = new newSampleYPDBEntities())
                {

                    List<WorkOrderFlowList> wflList = null;
                    foreach (Tb_Tech_Info inTech in listTech)
                    {
                        tb_Tech tech = DataEntites.tb_Tech.FirstOrDefault(t => t.TechId==inTech.TechId);

                        //if (tech == null)
                        //    throw new Exception("不存在“看样”节点");
                        if (!tech.WorkOrderFlowList.IsLoaded)
                        {
                            tech.WorkOrderFlowList.Load();
                        }
                        if (IsAllTask)//所有看样节点的任务
                        {
                            wflList = tech.WorkOrderFlowList.Where(wlf => wlf.Status == (int)OrderFlowListStatus.Useable).ToList();
                        }
                        else//当前员工在看样节点所接收的任务
                        {
                            wflList = tech.WorkOrderFlowList.Where(wl => wl.UserId == userId).ToList().Where(wlf => wlf.Status == (int)OrderFlowListStatus.Useable).ToList();
                        }
                        foreach (var wofl in wflList)
                        {
                            #region 数据加载
                            if (!wofl.orderInfoReference.IsLoaded)
                            {
                                wofl.orderInfoReference.Load();
                            }

                            if (wofl.orderInfo.status != (int)OrderInfoStatus.Doing)
                            {
                                continue;
                            }

                            if (!wofl.orderInfo.Tb_OrderBagReference.IsLoaded)
                            {
                                wofl.orderInfo.Tb_OrderBagReference.Load();
                            }
                            if (!wofl.orderInfo.Tb_ProductReference.IsLoaded)
                            {
                                wofl.orderInfo.Tb_ProductReference.Load();
                            }
                            if (!wofl.orderInfo.Tb_OrderBag.ShopReference.IsLoaded)
                            {
                                wofl.orderInfo.Tb_OrderBag.ShopReference.Load();
                            }
                            if (!wofl.tb_TechReference.IsLoaded)
                            {
                                wofl.tb_TechReference.Load();
                            }
                            if (!wofl.orderInfo.photoInfo.IsLoaded)
                            {
                                wofl.orderInfo.photoInfo.Load();
                            }

                            #endregion

                            TaskInfo ti = new TaskInfo()
                            {
                                OrderProductId = wofl.orderInfo.OrderProductId,
                                CtmName = wofl.orderInfo.CtmName,
                                OrderProductName = wofl.orderInfo.OrderProductName,
                                ProductNum = wofl.orderInfo.productNum,
                                Priority = (int)wofl.orderInfo.Priority,
                                ShopName = wofl.orderInfo.Tb_OrderBag.Shop.shopName,
                                ShopId = wofl.orderInfo.Tb_OrderBag.Shop.ShopId,
                                status = wofl.Status,
                                PageNum = wofl.orderInfo.photoInfo.Count,
                                ProductName = wofl.orderInfo.Tb_Product.ProductName,
                                ProductSize = wofl.orderInfo.Tb_Product.Width.ToString() + "*" + wofl.orderInfo.Tb_Product.Height.ToString(),
                                ProductRemark = wofl.orderInfo.Remark,
                                TechId = wofl.tb_Tech.TechId,
                                TechName = wofl.tb_Tech.TechName,
                                IsDeisgnTech = wofl.tb_Tech.IsDesign,
                                IsRebackOrder = false,
                                OrderPath = wofl.orderInfo.OrderPath,
                                workflowlistId = wofl.WorkFlowListId,
                                orderBagID = wofl.orderInfo.Tb_OrderBag.OrderBagId

                            };
                            if (wofl.AssignTime == wofl.ReceiveTime)
                            {
                                ti.SmallPicStatus = "未发样";
                            }
                            else
                            {
                                ti.SmallPicStatus = "已发样";
                            }


                            if (wofl.orderInfo.photoInfo.FirstOrDefault() != null)//产品有照片
                            {
                                if (!wofl.orderInfo.photoInfo.First().paperFaceReference.IsLoaded)
                                {
                                    wofl.orderInfo.photoInfo.First().paperFaceReference.Load();
                                }
                                if (!wofl.orderInfo.photoInfo.First().paperTypeReference.IsLoaded)
                                {
                                    wofl.orderInfo.photoInfo.First().paperTypeReference.Load();
                                }
                                ti.PaperFaceName = wofl.orderInfo.photoInfo.First().paperFace.Name;
                                ti.PaperTypeName = wofl.orderInfo.photoInfo.First().paperType.Name;
                                int printerId = (int)wofl.orderInfo.photoInfo.First().printerId;
                                printer printer = DataEntites.printer.FirstOrDefault(p => p.PrinterID == printerId);
                                if (printer != null)
                                {
                                    ti.PrinterName = printer.PName;
                                }
                                else
                                {
                                    ti.PrinterName = "";
                                }
                            }
                            else
                            {
                                ti.PaperFaceName = "";
                                ti.PaperTypeName = "";
                                ti.PrinterName = "";
                            }
                            ti.PhotoList = new List<PhotoInfo_GM>();
                            List<photoInfo> Plist = wofl.orderInfo.photoInfo.ToList();
                            foreach (var p in Plist)
                            {
                                if (!p.paperTypeReference.IsLoaded)
                                {
                                    p.paperTypeReference.Load();
                                }
                                if (!p.paperFaceReference.IsLoaded)
                                {
                                    p.paperFaceReference.Load();
                                }

                                PhotoInfo_GM pgm = new PhotoInfo_GM()
                                {
                                    Height = p.Height,
                                    IsEdit = false,
                                    PicPath = p.picPath,
                                    PhotoName = p.photoName,
                                    Width = p.Width,
                                    PhotoBarCode = p.PhotoBarCode,
                                    PhotoId = p.photoId,
                                    Remark = p.Remark,
                                    OldPicPath = p.OldPicPath,
                                    IsRebackPhoto = (p.status2 == (int)PhotoStatus2.innerReturn) ? true : false,
                                    PaperFaceName = p.paperFace.Name,
                                    PaperTypeName = p.paperType.Name
                                };
                                printer printer = DataEntites.printer.FirstOrDefault(pr => pr.PrinterID == p.printerId);
                                if (printer != null)
                                {
                                    pgm.PrinterName = printer.PName;
                                }
                                else
                                {
                                    pgm.PrinterName = "";
                                }

                                ti.PhotoList.Add(pgm);

                            }
                            ti.PhotoList = ti.PhotoList.OrderByDescending(p => p.IsRebackPhoto).ToList();//返单的照片在前面



                            taskList.Add(ti);
                        }
                    }
                }
            }
            taskList = taskList.OrderByDescending(t => t.Priority).ToList();
            return taskList;
        }

        public void MakSmallPic(TaskInfo taskInfo,BackgroundWorker work)
        {
            string smalPicPath = taskInfo.OrderPath + "\\看样";//看样文件夹路径
            if (!Directory.Exists(smalPicPath))        
            {
                Directory.CreateDirectory(smalPicPath);
            }
            GetSamllPic(taskInfo.PhotoList, smalPicPath,work);
        }

        private void GetSamllPic(List<PhotoInfo_GM> photoList,string smallPicPath,BackgroundWorker work)
        {
            RasterCodecs.Startup();
            RasterCodecs codecs = new RasterCodecs();
       
            RasterImage img;
            int index = 0;
            foreach (var item in photoList)
            {
                string desPath =smallPicPath +item.PicPath.Substring( item.PicPath.LastIndexOf("\\"));
                img = codecs.Load(item.PicPath);
                double width = (double)img.Width / img.XResolution;
                double height = (double)img.Height / img.YResolution;
                img.XResolution = 100;          
                img.YResolution = 100;

                SizeCommand cmd = new SizeCommand(Convert.ToInt32(img.XResolution * width), Convert.ToInt32(img.YResolution * height), RasterSizeFlags.Resample);
                cmd.Run(img);
                codecs.Save(img,desPath , RasterImageFormat.Jpeg,24);
                index ++;
                work.ReportProgress(index);
            }
            RasterCodecs.Shutdown();
        }

        /// <summary>
        /// 标记为已发样
        /// </summary>
        /// <param name="taskInfoList"></param>
        public void SendSmallPic(List<TaskInfo> taskInfoList)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                foreach (var item in taskInfoList)
                {
                    WorkOrderFlowList wfl = db.WorkOrderFlowList.FirstOrDefault(w=>w.WorkFlowListId ==item.workflowlistId);
                    wfl.ReceiveTime = DateTime.Now;
                }
                db.SaveChanges();
            }
        }

        /// <summary>
        /// 退回给设计
        /// </summary>
        /// <param name="taskInfo"></param>
        /// <param name="strMsg"></param>
        /// <returns></returns>
        public bool ReBackTask(TaskInfo taskInfo,string rebackRemark, out string strMsg)
        {
            strMsg = string.Empty;
          
                //1、检查是否有一节点，并且上一节点不能为开始
                //2、将当前结点的userid=0\status=0
                //3、让上一节点的status=0
                //4、修改orderInfo的Remark
                using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
                {
                    orderInfo curOi = dataBase.orderInfo.FirstOrDefault(o => o.OrderProductId == taskInfo.OrderProductId);
                    curOi.Remark = curOi.Remark + "\n" + rebackRemark;//退回原因
                    if (curOi == null)
                    {
                        strMsg = "没有找到该产品，请检查或是重启程序！";
                        return false;
                    }

                    if (!curOi.WorkOrderFlowList.IsLoaded)
                    {
                        curOi.WorkOrderFlowList.Load();
                    }
                    WorkOrderFlowList curWfl = curOi.WorkOrderFlowList.ToList().FirstOrDefault(wf => wf.Status == (int)OrderFlowListStatus.UseableAccept || wf.Status == (int)OrderFlowListStatus.Useable);
                    if (curWfl == null)
                    {
                        strMsg = "找不到当前可用的结点，请检查或是重启程序！";
                        return false;
                    }
                    else
                    {
                        //上一个节点
                        List<WorkOrderFlowList> preWflList = curOi.WorkOrderFlowList.ToList().Where(w => w.WorkOrder < curWfl.WorkOrder).OrderByDescending(w => w.WorkOrder).ToList();

                        if (preWflList.Count < 2)
                        {
                            strMsg = "这是第一个节点，没有上一节点，请检查！";
                            return false;
                        }


                        WorkOrderFlowList preWfl = preWflList.FirstOrDefault();
                        if (preWfl.WorkOrder == 1)
                        {
                            strMsg = "不能退回到开始节点，请重新选择！";
                            return false;
                        }
                       
                        preWfl.Status = (int)OrderFlowListStatus.Useable;

                        curWfl.Status = (int)OrderFlowListStatus.Wait;
                        curWfl.ReceiveTime = curWfl.AssignTime;
                        curWfl.UserId = 0;
                    }

                    try
                    {
                        dataBase.SaveChanges();
                        return true;
                    }
                    catch (Exception ex)
                    {
                        strMsg = "在保存数据库时出错," + ex.Message;
                        return false;
                    }
                
             }
        }

        /// <summary>
        /// 完成任务
        /// </summary>
        /// <param name="curTechId"></param>
        /// <param name="userid"></param>
        /// <param name="orderProductId"></param>
        /// <param name="epByPhotoSpecInfoList"></param>
        /// <param name="workshop"></param>
        /// <returns></returns>
        public bool CompleteWork(int curTechId, int userid, int orderProductId)
        {

            return _workFlowBll.OverCurTechForGroupMember(curTechId, userid, orderProductId, GetEPByPhotoSpecInfoList(), GetWorkShopInfo());
        }


        /// <summary>
        /// 获取按照片规格统计名称列表
        /// </summary>
        /// <returns></returns>
        private List<EPByPhotoSpecInfo> GetEPByPhotoSpecInfoList()
        {
            List<EPByPhotoSpecInfo> list = new List<EPByPhotoSpecInfo>();
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    List<New_EmployeePerformance_SpecInfo> epList = db.New_EmployeePerformance_SpecInfo.ToList();
                    foreach (var item in epList)
                    {
                        EPByPhotoSpecInfo epByphotoSpecInfo = new EPByPhotoSpecInfo()
                        {
                            MaxArea = item.MaxArea,
                            MinArea = item.MinArea,
                            SpecId = item.SpecId,
                            SpecName = item.SpecName
                        };
                        list.Add(epByphotoSpecInfo);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return list;
        }


        /// <summary>
        /// 获得车间信息
        /// </summary>
        /// <returns></returns>
        public WorkShop_Info GetWorkShopInfo()
        {
            WorkShop_Info wsInfo = null;
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    WorkShop ws = db.WorkShop.FirstOrDefault();
                    if (ws != null)
                    {
                        wsInfo = new WorkShop_Info()
                        {
                            Address = ws.Address,
                            AutoAssignShop = ws.AutoAssignShop,
                            CustomerTel = ws.CustomerTel,
                            Email = ws.Email,
                            FinanceTel = ws.FinanceTel,
                            QQ = ws.QQ,
                            Remark = ws.Remark,
                            WorkShopName = ws.WorkShopName,
                            InsertEPByPhotoSpec = ws.InsertEmployeePerfermanceByPhotoSpec,
                            ControlNonexistenceTechByPriority = ws.ControlNonexistenceTechByPriority
                        };
                    }
                }
            }
            catch
            {

            }
            return wsInfo;
        }


        public List<Tb_Tech_Info> GetAllTech()
        {
            List<Tb_Tech_Info> list = new List<Tb_Tech_Info>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                int techtype=(int)TechType.GroupSample;
                List<tb_Tech> listDB = db.tb_Tech.Where(t => t.TechType == techtype).ToList();
                foreach (tb_Tech t in listDB)
                {
                    list.Add(new Tb_Tech_Info() { TechId=t.TechId,TechName=t.TechName});
                }
            }
            return list;
        }
    }
}
